package org.aurora.core.common.util;

import org.apache.commons.lang3.StringUtils;
import org.aurora.core.common.SchedulerConstant;

public class HashSlotUtil {
    public static int reHashCode(String str) {
        if (str == null) {
            return 0;
        }

        int hashCode = stringHashCode(str);
        return (hashCode & (hashCode >> 16)) & (SchedulerConstant.SCHEDULER_HASH_SLOT_SIZE - 1);
    }

    /**
     * @since jdk 8 java.lang.String#hashCode
     * 拷贝自 jdk 8 String 类的 hashcode 防止算法改变导致 appcode 落入的 hash 槽不一致
     * @param str
     * @return
     */
    private static int stringHashCode(String str) {
        if (StringUtils.isBlank(str)) {
            return 0;
        }
        int h = 0;

        char[] value = str.toCharArray();

        for (char c : value) {
            h = 31 * h + c;
        }
        return h;
    }

    public static void main(String[] args) {
        System.out.println(reHashCode("testAppName"));
    }
}
